package com.mms.service.impl;

import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.mms.dao.IResourcesDao;
import com.mms.dao.IRoleInfoDao;
import com.mms.dao.IUserInfoDao;
import com.mms.pojo.Resources;
import com.mms.pojo.RoleInfo;
import com.mms.service.IResourcesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 陈林鹏
 * @since 2021-04-14
 */
@Service
public class ResourcesServiceImpl extends ServiceImpl<IResourcesDao, Resources> implements IResourcesService {

    /**
     * 用户信息表
     */
    @Autowired
    IUserInfoDao userInfoDao;
    /**
     * roleInfo 角色信息表
     */
    @Autowired
    IRoleInfoDao roleInfoDao;
    /**
     * resources 资源表
     */
    @Autowired
    IResourcesDao resourcesDao;

    /**
     * 通过 userinfoId 获取 resources
     *
     * @param userinfoId
     * @return
     */
    public List<Resources> getResourcesByUserinfo(Integer userinfoId) {
        //获取
        Integer roleInfoId = userInfoDao.getRoleInfoIdByUserinfoId(userinfoId);

        RoleInfo roleInfo = roleInfoDao.selectById(roleInfoId);
        return resourcesDao.getResourcesByRoleInfoId(roleInfo.getId());
    }

    /**
     * 分析子资源 关系
     *
     * @param resourcesList 子资源
     * @return
     */
    public Map<Resources, List<Resources>> parseHierarchy(List<Resources> resourcesList) {
        List<Resources> tempData = new LinkedList<Resources>();
        for (Resources resources : resourcesList) {
            if (resources.getParentId() == -1) {
                tempData.add(resources);
                continue;
            }
            while (resources != null) {
                Integer parentId = resources.getParentId();
                resources = selectById(parentId);
                if (resources != null && !tempData.contains(resources)) {
                    tempData.add(resources);
                    break;
                }
            }
        }
        Map<Resources, List<Resources>> retData = new HashMap<>();
        for (Resources resources : tempData) {
            List<Resources> tempResources = new LinkedList<>();
            for (Resources resources2 : resourcesList) {
                if (resources.getId() == resources2.getParentId()) {
                    tempResources.add(resources2);
                }
            }
            retData.put(resources, tempResources);
        }
        return retData;
    }
}
